<script setup lang="ts">
import { reactive, ref } from 'vue';
import type { FormInst } from 'naive-ui';
import { useMessage, NButton, NCard, NForm, NFormItem, NInput } from 'naive-ui';
import statusCode from '../api/statusCode';
import { getToken } from '../util/token';
import { handleNoToken, listAllError } from '../util/handler';
import { createStore } from '../api/store';

const emit = defineEmits<{
  (e: 'closeStore'): void
  (e: 'refreshList'): void
}>();

const formRef = ref<FormInst | null>(null);
const message = useMessage();

const formValue = reactive({
  storeName: ''
});

const rules = {
  storeName: {
      required: true,
      message: '请输入店铺名称',
      trigger: 'input'
  },
};

const formValidate = () => {
  return formRef.value?.validate();
};

const handleButtonClick = async () => {
  try {
    await formValidate();

    const token = getToken();
    if (!token) {
      handleNoToken(message);
      return;
    }

    try {
      const resp = await createStore({ ...formValue, token });

      if (resp.status === statusCode.SUCCESS) {
        message.success(`成功创建店铺${formValue.storeName}`, {
          duration: 1500,
          onAfterLeave: () => {
            emit('refreshList');
            emit('closeStore');
          }
        });
      } else {
        throw new Error(`错误码 ${resp.status}`);
      }
    } catch (error) {
      message.error("" + error);
    }

  } catch (errors) {
    if (errors instanceof Array) {
      listAllError(errors, message);
    } else {
      throw errors;
    }
  }
};

const handleCloseBtnClick = () => emit('closeStore');
</script>

<template>
  <n-card title="创建店铺">
    <n-form
      :model="formValue"
      :rules="rules"
      :show-require-mark="false"
      ref="formRef"
    >
      <n-form-item
        label="店铺名称"
        path="storeName"
      >
        <n-input
          type="text"
          v-model:value="formValue.storeName"
          placeholder="店铺名称"
          :maxlength="16"
        />
      </n-form-item>
      <n-form-item>
        <n-button
          @click="handleButtonClick"
          type="primary"
          attr-type="submit"
        >
          创建
        </n-button>
        <n-button
          @click="handleCloseBtnClick"
          type="default"
          attr-type="button"
        >
          取消
        </n-button>
      </n-form-item>
    </n-form>
  </n-card>
</template>

<style scoped>
</style>
